<template>
	<view>
		<view class="goods-list">
			<view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
				<my-goods :goods="goods"></my-goods>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 请求参数对象
				queryObj: {
					query: '', // 查询关键词
					cid: '', // 商品分类Id
					pagenum: 1, // 页码值
					pagesize: 10 // 每页显示多少条数据
				},
				goodsList: [], // 商品列表的数据
				total: 0, // 总数量，用来实现分页

				isloading: false, // 是否正在请求数据
			};
		},

		onLoad(options) {
			this.queryObj.query = options.query || ''
			this.queryObj.cid = options.cid || ''
			this.getGoodsList()
		},

		// 下拉刷新
		onPullDownRefresh() {
			this.queryObj.pagenum = 1
			this.total = 0
			this.isloading = false
			this.goodsList = []
			this.getGoodsList(() => uni.stopPullDownRefresh())
		},


		// 上拉加载各部
		onReachBottom() {
			// 判断是否含有下一页的数据
			if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) {
				return uni.$showmessage('数据加载完毕！')
			}
			if (this.isloading) return // 节流阀
			this.queryObj.pagenum += 1 // 让页码值自增 +1
			this.getGoodsList() // 重新获取列表数据
		},

		methods: {

			async getGoodsList(cb) {
				this.isloading = true
				const {
					data: res
				} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
				this.isloading = false
				cb && cb() // 如果 cb 的函数存在就去调用
				if (res.meta.status !== 200) return uni.$showmessage()
				// 为数据赋值，和旧数据拼接
				this.goodsList = [...this.goodsList, ...res.message.goods]
				this.total = res.message.total
			},

			gotoDetail(goods) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
				})
			}
		}


	}
</script>

<style lang="scss">

</style>
